package com.nstskj.study.netty.tcp.netty.protocol.message.in.msg;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.HexUtil;
import com.nstskj.study.netty.tcp.netty.protocol.annotation.MessageCommandAnnotation;
import com.nstskj.study.netty.tcp.netty.protocol.endpoint.data.EndpointData;
import com.nstskj.study.netty.tcp.netty.protocol.enums.IotDeviceProtocolCmdEnum;
import com.nstskj.study.netty.tcp.netty.protocol.message.in.msg.base.AbstractInputNetTcpMessage;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/20 20:58
 * @Description 设备端点数据上报
 */
@Data
@MessageCommandAnnotation(value = IotDeviceProtocolCmdEnum.DEVICE_ENDPOINT_PUSH)
public class DeviceEndpointPushCmdMsg extends AbstractInputNetTcpMessage {

    /**
     * 端点数据
     */
    private List<EndpointData> endpointDataList;

    /**
     * 命令数据自定义处理
     */
    @Override
    public void decoderCmdData() {
        //得到命令数据
        byte[] cmdData = this.getCmdData();
        this.endpointDataList = new ArrayList<>();
        int cmdDataIndex = 0;
        int cmdDataLen = cmdData.length;
        while (cmdDataIndex < cmdDataLen) {
            EndpointData endpointData = new EndpointData();
            endpointData.setTimestamp(System.currentTimeMillis());
            endpointData.setTimestampStr(DatePattern.NORM_DATETIME_FORMAT.format(endpointData.getTimestamp()));
            short address = (short) (cmdData[cmdDataIndex] * 256 + cmdData[cmdDataIndex + 1]);
            cmdDataIndex += 2;
            endpointData.setAddress(address);
            int buffLen = (short) (cmdData[cmdDataIndex] * 256 + cmdData[cmdDataIndex + 1]);
            cmdDataIndex += 2;
            if (buffLen > 0) {
                byte[] bytes = new byte[buffLen];
                System.arraycopy(cmdData, cmdDataIndex, bytes, 0, bytes.length);
                String hexStr = HexUtil.encodeHexStr(bytes, false);
                endpointData.setHexStr(hexStr);
                cmdDataIndex += buffLen;
            }
            endpointDataList.add(endpointData);
        }
    }
}
